package com.cmhi.softmbh.provider;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.cmhi.softmbh.MyApplication;
import com.softmbh.kellyplatform.util.AppUtils;

public class DBUtil {
    private static Uri uri = Provider.HuaWeiColumns.CONTENT_URI;

    //查询
    public static String query(String name) {
        if (name == null || name.isEmpty()) {
            return "";
        }
        String result = "";
        Cursor cursor = MyApplication.myApplication.getContentResolver().query(
                uri, null, "name=?", new String[]{name}, null);
        if (cursor == null) {
            return "";
        }
        while (cursor.moveToNext()) {
            String value = cursor.getString(cursor.getColumnIndex("value"));
            result = ((value == null) ? "" : value);
        }
        cursor.close();
        AppUtils.debugLog("query name : " + name + ", value : " + result);
        return result;
    }

    //更新
    public static void update(String name, String value) {
        AppUtils.debugLog("update name : " + name + ", value : " + value);
        if (name == null || name.isEmpty() || value == null) {
            return;
        }
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("value", value);
        if (isKeyExit(name)) {
            MyApplication.myApplication.getContentResolver().update(uri, values, "name=?", new String[]{name});
        } else {
            Uri uri1 = MyApplication.myApplication.getContentResolver().insert(uri, values);
            String lastPath = uri1 != null ? uri1.getLastPathSegment() : null;
            if (TextUtils.isEmpty(lastPath)) {
                AppUtils.debugLog("insert failure!");
            } else {
                AppUtils.debugLog("insert success! the id is " + lastPath);
            }
        }
    }

    //删除
    public static void delete(String name) {
        AppUtils.debugLog("delete name : " + name);
        if (name == null || name.isEmpty()) {
            return;
        }
        if (isKeyExit(name)) {
            MyApplication.myApplication.getContentResolver().delete(uri, "name=?", new String[]{name});
        }
    }

    private static boolean isKeyExit(String key) {
        boolean result = false;
        Cursor cursor = MyApplication.myApplication.getContentResolver().query(
                uri, null, "name=?", new String[]{key}, null);
        if (cursor == null) {
            return false;
        } else if (cursor.getCount() > 0) {
            result = true;
        }
        cursor.close();
        return result;
    }
}
